package model

import (
	"github.com/jinzhu/gorm"
	"github.com/satori/go.uuid"
	"time"
)

type BillCategory struct {
	BaseModel
	Name     string `json:"name"`
	ParentId string `json:"parentId"`
	Level    int    `json:"level"`
}

func (b BillCategory) TableName() string {
	return "tb_bill_category"
}

func (b *BillCategory) Create() error {
	return DB.Self.Create(&b).Error
}

func (b *BillCategory) BeforeCreate(scope *gorm.Scope) error {
	u4, _ := uuid.NewV4()
	scope.SetColumn("Id", u4.String())
	scope.SetColumn("created_time", time.Now())
	scope.SetColumn("created_by", "system")
	scope.SetColumn("updated_time", time.Now())
	scope.SetColumn("updated_by", "system")
	return nil
}

func (b *BillCategory) BeforeUpdate() error {
	b.UpdatedTime = time.Now()
	return nil
}

func DeleteBillCategory(id string) error {
	billCategory := BillCategory{}
	billCategory.Id = id
	return DB.Self.Delete(&billCategory).Error
}

func (b *BillCategory) Update() error {
	return DB.Self.Save(&b).Error
}

func ListBillCategory(offset, limit int) ([]*BillCategory, uint64, error) {
	if limit == 0 {
		limit = 10
	}
	billCategories := make([]*BillCategory, 0)

	var count uint64
	if err := DB.Self.Model(&BillCategory{}).Count(&count).Error; err != nil {
		return billCategories, count, err
	}
	if err := DB.Self.Offset(offset).Limit(limit).Order("created_time asc").Find(&billCategories).Error; err != nil {
		return billCategories, count, err
	}

	return billCategories, count, nil
}

func GetBillCategoryById(id string) (*BillCategory, error) {
	var billCategory BillCategory
	d := DB.Self.First(&billCategory)
	return &billCategory, d.Error
}
